import { useEffect, useRef, useState } from "react";
import {
  Button,
  Card,
  Drawer,
  Form,
  Input,
  Space,
  Select,
  DatePicker,
  Spin,
  Tabs,
  Row,
  Col,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import reportService, {
  type PageListReq,
} from "@/api/services/eam/maintainReportService";
import type { EamMaintainReport } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import useDictionary from "@/hooks/system/useDictionary";
import TableDictTag from "@/components/grid/TableDictTag";
import EamMaintainReportLinePage, {
  type EamMaintainReportLineHandles,
} from "./line";
import CustomTable from "@/components/grid/CustomTable";
import SingleEquipmentSelect from "@/pages/components/selector/SingleEquipmentSelect";
import { SearchOutlined } from "@ant-design/icons";
import { EamEquipment } from "../equipment/entity";
import dayjs from "dayjs";

const { TextArea } = Input;

export default function EamMaintainReportPage() {
  const lineRef = useRef<EamMaintainReportLineHandles>(null);

  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    code: undefined,
    equipmentId: undefined,
    status: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<EamMaintainReport[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingData, setEditingData] = useState<EamMaintainReport | null>(
    null
  );
  const [form] = Form.useForm();
  const [isView, setIsView] = useState(true);
  const [isMaintain, setIsMaintain] = useState(false);

  const [selectEquipmentVisible, setSelectEquipmentVisible] = useState(false);

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 405;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  const statusOptions = useDictionary("common_order_status");
  const maintainResultOptions = useDictionary("check_result");

  const columns: ColumnsType<EamMaintainReport> = [
    {
      title: "保养单号",
      width: 120,
      key: "code",
      dataIndex: "code",
    },
    {
      title: "设备编码",
      width: 120,
      key: "equipmentCode",
      dataIndex: "equipmentCode",
    },
    {
      title: "设备名称",
      width: 120,
      key: "equipmentName",
      dataIndex: "equipmentName",
    },
    {
      title: "状态",
      width: 120,
      key: "status",
      dataIndex: "status",
      render: (_, record) => (
        <TableDictTag
          dictCode="common_order_status"
          value={record.status ?? ""}
        />
      ),
    },
    {
      title: "备注",
      width: 120,
      key: "remark",
      dataIndex: "remark",
    },
    {
      title: "开始时间",
      width: 120,
      key: "startDate",
      dataIndex: "startDate",
    },
    {
      title: "结束时间",
      width: 120,
      key: "endDate",
      dataIndex: "endDate",
    },
    {
      title: "保养结果",
      width: 120,
      key: "maintainResult",
      dataIndex: "maintainResult",
      render: (_, record) => (
        <TableDictTag
          dictCode="check_result"
          value={record.maintainResult ?? ""}
        />
      ),
    },
    {
      title: "保养人",
      width: 120,
      key: "maintainUser",
      dataIndex: "maintainUser",
    },
    {
      title: "保养时间",
      width: 120,
      key: "maintainTime",
      dataIndex: "maintainTime",
    },
    {
      title: "操作",
      fixed: "right",
      key: "operation",
      align: "center",
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            {t("common.view")}
          </Button>
          {record?.status === "PREPARE" && (
            <Button type="link" onClick={() => handleMaintain(record)}>
              保养
            </Button>
          )}
        </Space>
      ),
    },
  ];

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    reportService
      .pageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  //触发编辑按钮
  const handleMaintain = (eamMaintainReport: EamMaintainReport) => {
    setEditingData(eamMaintainReport);
    form.setFieldsValue(eamMaintainReport);
    setDrawerVisible(true);
    setIsView(false);
    setIsMaintain(true);
  };

  //触发视图按钮
  const handleView = (eamMaintainReport: EamMaintainReport) => {
    setEditingData(eamMaintainReport);
    form.setFieldsValue(eamMaintainReport);
    setIsView(true);
    setDrawerVisible(true);
  };

  //保存表单数据
  const handleSave = async (values: EamMaintainReport) => {
    try {
      setSubmitLoading(true);

      //设备保养记录明细
      const deleteLineIds = lineRef.current?.getDeleteIds();
      const addLines = lineRef.current?.getAddList();
      const updateLines = lineRef.current?.getUpdateList();

      const data = {
        ...values,
        id: editingData?.id,
        deleteLineIds: deleteLineIds,
        addLines: addLines,
        updateLines: updateLines,
      };
      if (editingData) {
        await reportService.update(data);
        toast.success("更新设备保养记录成功");
      } else {
        await reportService.add(data);
        toast.success("创建设备保养记录成功");
      }
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleSubmit = async () => {
    try {
      setSubmitLoading(true);

      const values = await form.getFieldsValue();

      //设备保养记录明细
      const updateLines = lineRef.current?.getUpdateList();

      const data = {
        ...values,
        id: editingData?.id,
        updateLines: updateLines,
      };

      await reportService.submit(data);
      toast.success("设备保养记录提交成功");

      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingData(null);
    form.resetFields();
  };

  const handleAdd = () => {
    setEditingData(null);
    form.resetFields();
    setDrawerVisible(true);
    setIsView(false);
    setIsMaintain(false);
  };

  // 审核
  const handleApprove = async () => {
    if (selectedRowKeys.length === 0) {
      toast.error("请先选择要审核的保养记录");
      return;
    }

    const selectedRows = list.filter((item) =>
      selectedRowKeys.includes(item.id)
    );
    const allSameStatus = selectedRows.every(
      (row) => row.status === selectedRows[0]?.status
    );
    if (!allSameStatus) {
      toast.error("请选择状态一致的保养记录进行操作");
      return;
    }

    const allDraft = selectedRows.every((row) => row.status === "APPROVING");
    if (!allDraft) {
      toast.error("只有审批中的保养记录才能审核");
      return;
    }

    try {
      setLoading(true);
      await reportService.updateStatus(selectedRowKeys, "APPROVED");
      toast.success("审核成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`审核失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 取消审核
  const cancleApprove = async () => {
    if (selectedRowKeys.length === 0) {
      toast.error("请先选择要取消审核的保养记录");
      return;
    }

    const selectedRows = list.filter((item) =>
      selectedRowKeys.includes(item.id)
    );
    const allSameStatus = selectedRows.every(
      (row) => row.status === selectedRows[0]?.status
    );
    if (!allSameStatus) {
      toast.error("请选择状态一致的保养记录进行操作");
      return;
    }

    const allDraft = selectedRows.every((row) => row.status === "APPROVED");
    if (!allDraft) {
      toast.error("只有已审核的保养记录才能取消审核");
      return;
    }

    try {
      setLoading(true);
      await reportService.updateStatus(selectedRowKeys, "APPROVING");
      toast.success("取消审核成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`取消审核失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 作废
  const handleCancelSubmit = async () => {
    if (selectedRowKeys.length === 0) {
      toast.error("请先选择要取消提交的保养记录");
      return;
    }

    const selectedRows = list.filter((item) =>
      selectedRowKeys.includes(item.id)
    );
    const allSameStatus = selectedRows.every(
      (row) => row.status === selectedRows[0]?.status
    );
    if (!allSameStatus) {
      toast.error("请选择状态一致的保养记录进行操作");
      return;
    }

    const allDraft = selectedRows.every((row) => row.status === "APPROVING");
    if (!allDraft) {
      toast.error("只有审批中的保养记录才能取消提交");
      return;
    }

    try {
      setLoading(true);
      await reportService.updateStatus(selectedRowKeys, "PREPARE");
      toast.success("取消提交成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`取消提交失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    try {
      setLoading(true);
      await reportService.remove(selectedRowKeys);
      toast.success("删除设备保养记录成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`删除失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const showEquipmentSelect = () => {
    setSelectEquipmentVisible(true);
  };
  const handleSelectEquipment = (item: EamEquipment) => {
    setSelectEquipmentVisible(false);
    form.setFieldsValue({
      equipmentId: item?.id,
      equipmentName: item?.name,
      equipmentCode: item?.code,
    });
  };

  return (
    <Spin spinning={submitLoading} tip="数据提交中..." size="large">
      <Card className="mb-4">
        <Form
          layout="inline"
          onFinish={(values) => {
            setQueryParams((prev) => ({
              ...prev,
              ...values,
              page: 1,
            }));
          }}
        >
          <Form.Item name="code" label="保养单号">
            <Input allowClear placeholder="请输入保养单号" />
          </Form.Item>

          <Form.Item name="equipmentId" label="设备ID">
            <Input allowClear placeholder="请输入设备ID" />
          </Form.Item>

          <Form.Item name="status" label="状态">
            <Select
              options={statusOptions}
              allowClear
              style={{ width: 170 }}
              placeholder="请选择状态"
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setQueryParams({ page: 1, pageSize: 10 });
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <div className="h-4" />
      <Card>
        <CustomTable
          loading={loading}
          columnsConfig={columns}
          dataSource={list}
          total={total}
          selectedRowKeys={selectedRowKeys}
          setSelectedRowKeys={setSelectedRowKeys}
          current={queryParams.page}
          pageSize={queryParams.pageSize}
          onRefresh={fetchPageList}
          onPageChange={handlePageChange}
          selectable
          toolbarButtons={
            <>
              <Button type="primary" onClick={handleAdd}>
                新增
              </Button>
              <Button
                type="primary"
                disabled={selectedRowKeys.length === 0}
                onClick={handleApprove}
              >
                审核
              </Button>
              <Button
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={cancleApprove}
              >
                取消审核
              </Button>
              <Button
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={handleCancelSubmit}
              >
                取消提交
              </Button>
              <Button
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={handleDelete}
              >
                删除
              </Button>
            </>
          }
          scroll={{ y: tableScrollY }}
        />
      </Card>
      <Drawer
        title={editingData ? "编辑设备保养记录" : "新增设备保养记录"}
        width={1000}
        open={drawerVisible}
        onClose={handleDrawerClose}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={handleDrawerClose}>取消</Button>
            {!isView && (
              <>
                <Button
                  type="primary"
                  loading={submitLoading}
                  onClick={() => form.submit()}
                >
                  保存
                </Button>
                <Button
                  type="primary"
                  loading={submitLoading}
                  onClick={() => handleSubmit()}
                >
                  提交
                </Button>
              </>
            )}
          </div>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onFinish={handleSave}
          disabled={isView}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="equipmentId" label="设备" hidden>
                <Input />
              </Form.Item>
              <Form.Item name="equipmentCode" label="设备编码">
                <Input.Search
                  placeholder="请选择设备"
                  allowClear
                  enterButton={<SearchOutlined />}
                  onSearch={showEquipmentSelect}
                  disabled={isMaintain || isView}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="equipmentName" label="设备名称">
                <Input disabled={isMaintain || isView} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="startDate"
                label="开始时间"
                getValueFromEvent={(value) => {
                  return value ? value.format("YYYY-MM-DD") : null;
                }}
                getValueProps={(value) => ({
                  value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
                })}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  format="YYYY-MM-DD"
                  onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
                  disabled={isMaintain || isView}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="endDate"
                label="结束时间"
                getValueFromEvent={(value) => {
                  return value ? value.format("YYYY-MM-DD") : null;
                }}
                getValueProps={(value) => ({
                  value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
                })}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  format="YYYY-MM-DD"
                  onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
                  disabled={isMaintain || isView}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="maintainUser" label="保养人">
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="maintainTime"
                label="保养时间"
                getValueFromEvent={(value) => {
                  return value ? value.format("YYYY-MM-DD") : null;
                }}
                getValueProps={(value) => ({
                  value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
                })}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  format="YYYY-MM-DD"
                  onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
                  disabled
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="maintainResult" label="保养结果">
                <Select options={maintainResultOptions} allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="status" label="状态">
                <Select options={statusOptions} allowClear />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={24}>
              <Form.Item
                name="remark"
                label="备注"
                labelCol={{ span: 3 }}
                wrapperCol={{ span: 21 }}
              >
                <TextArea />
              </Form.Item>
            </Col>
          </Row>

          <Tabs
            defaultActiveKey="1"
            items={[
              {
                key: "1",
                label: "保养记录",
                children: (
                  <EamMaintainReportLinePage
                    ref={lineRef}
                    parentId={editingData?.id}
                  />
                ),
              },
            ]}
          />
        </Form>

        <SingleEquipmentSelect
          open={selectEquipmentVisible}
          onCancel={() => setSelectEquipmentVisible(false)}
          onOk={(item) => handleSelectEquipment(item)}
        />
      </Drawer>
    </Spin>
  );
}
